package com.example.qxfw.nyqx.service.impl;

import com.example.qxfw.nyqx.dto.AgriSrvFcstDto;
import com.example.qxfw.common.entity.ny.AgriSrvFcst;
import com.example.qxfw.nyqx.mapper.AgriSrvFcstMapper;
import com.example.qxfw.nyqx.service.AgriSrvFcstService;
import com.example.qxfw.common.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class AgriSrvFcstServiceImpl implements AgriSrvFcstService {

    @Autowired
    private AgriSrvFcstMapper agriSrvFcstMapper;

    @Override
    public List<AgriSrvFcst> getList(String forecastDate, String timeChar, String indexName) {
        return agriSrvFcstMapper.forecastQuery(Timestamp.valueOf(forecastDate), timeChar, indexName);
    }

    @Override
    public Integer delete(String forecastDate, String timeChar, String indexName) {
        return agriSrvFcstMapper.delete(DateUtil.localDateTimeToDate(DateUtil.stringToLocalDateTime(forecastDate)), timeChar, indexName);
    }

    @Override
    public AgriSrvFcst save(AgriSrvFcst agriSrvFcst) {
        int rows = agriSrvFcstMapper.insert(agriSrvFcst);
        return rows != 0 ? agriSrvFcst : null;
    }

    @Override
    public List<AgriSrvFcstDto> forecastQuery(final String forecastDate, final String timeChar, final String indexName) {
        List<AgriSrvFcst> agriSrvFcstList = agriSrvFcstMapper.forecastQuery(DateUtil.localDateTimeToDate(DateUtil.stringToLocalDateTime(forecastDate)), timeChar, indexName);
        System.err.println(agriSrvFcstList.size());

        List<AgriSrvFcstDto> agriSrvFcstDtoList = new ArrayList<>();
        agriSrvFcstList.forEach(agriSrvFcst -> {
            AgriSrvFcstDto agriSrvFcstDto = new AgriSrvFcstDto();
            agriSrvFcstDto.setFarmservicesite(agriSrvFcst.getFarmservicesite());
            agriSrvFcstDto.setForecastdate(agriSrvFcst.getForecastdate().toString() + " " + agriSrvFcst.getTimechar());
            agriSrvFcstDto.setLat(agriSrvFcst.getLat());
            agriSrvFcstDto.setLon(agriSrvFcst.getLon());
            agriSrvFcstDto.setIndexname(agriSrvFcst.getIndexname());
            agriSrvFcstDto.setIndexlevel(agriSrvFcst.getIndexlevel());
            agriSrvFcstDto.setExplain(agriSrvFcst.getExplain());
            agriSrvFcstDto.setStationname(agriSrvFcst.getStationname());
            agriSrvFcstDtoList.add(agriSrvFcstDto);
        });
        return agriSrvFcstDtoList.stream()
                .distinct()
                .collect(Collectors.toList());
    }
}
